import 'package:blurb/pages/community/community.dart';
import 'package:blurb/pages/message/message.dart';
import 'package:blurb/pages/personal/personal.dart';
import 'package:flutter/material.dart';
import 'package:blurb/common/values/images.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:blurb/pages/home/home.dart';

class MainPage extends StatefulWidget {
  const MainPage({super.key});

  @override
  State<MainPage> createState() => _MainPageState();
}

class _MainPageState extends State<MainPage> with SingleTickerProviderStateMixin {
  int _currentIndex = 0;
  AnimationController? _animationController;
  Animation<double>? _scaleAnimation;

  // Page list
  final List<Widget> _pages = [
    const HomePage(),
    const CommunityPage(),
    const MessagePage(),
    const PersonalPage(),
  ];

  @override
  void initState() {
    super.initState();
    // 确保在initState中初始化动画控制器
    _animationController = AnimationController(
      vsync: this,
      duration: const Duration(milliseconds: 200),
    );
    _scaleAnimation = Tween<double>(begin: 1.0, end: 0.9).animate(
      CurvedAnimation(
        parent: _animationController!,
        curve: Curves.easeInOut,
      ),
    );
    _animationController!.addStatusListener((status) {
      if (status == AnimationStatus.completed) {
        _animationController!.reverse();
      }
    });
  }

  @override
  void dispose() {
    // 确保在dispose前检查是否已初始化
    _animationController?.dispose();
    super.dispose();
  }

  void _onNavItemTap(int index) {
    if (_currentIndex != index) {
      _animationController?.forward(from: 0.0);
      setState(() {
        _currentIndex = index;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    // 获取底部安全区域高度
    final bottomPadding = MediaQuery.of(context).padding.bottom;
    
    return Scaffold(
      body: Stack(
        children: [
          // Main content
          _pages[_currentIndex],
          
          // Custom bottom navigation bar
          Positioned(
            left: 0,
            right: 0,
            bottom: 0,
            child: _buildCustomNavigationBar(bottomPadding),
          ),
        ],
      ),
    );
  }

  Widget _buildCustomNavigationBar(double bottomPadding) {
    return Stack(
      children: [
        // 蓝色底层
        Container(
          height: 60.h + bottomPadding,
          decoration: BoxDecoration(
            color: const Color(0xFF60C3FF),
            borderRadius: BorderRadius.only(
              topLeft: Radius.circular(32.r),
              topRight: Radius.circular(32.r),
            ),
          ),
        ),
        // 黑色上层
        Positioned(
          top: 3.h,
          left: 0,
          right: 0,
          height: 58.h + bottomPadding,
          child: Container(
            decoration: BoxDecoration(
              color: Colors.black,
              borderRadius: BorderRadius.only(
                topLeft: Radius.circular(30.r),
                topRight: Radius.circular(30.r),
              ),
            ),
            child: ClipRect(
              child: Column(
                mainAxisSize: MainAxisSize.min,
                children: [
                  SizedBox(
                    height: 58.h,
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceAround,
                      children: [
                        _buildNavItem(0, MIP.home, MIP.homeActive, 'Home'),
                        _buildNavItem(1, MIP.community, MIP.communityActive, 'Community'),
                        _buildNavItem(2, MIP.message, MIP.messageActive, 'Message'),
                        _buildNavItem(3, MIP.personal, MIP.personalActive, 'Profile'),
                      ],
                    ),
                  ),
                  // 底部安全区域的空白
                  SizedBox(height: bottomPadding),
                ],
              ),
            ),
          ),
        ),
      ],
    );
  }

  Widget _buildNavItem(
    int index,
    String icon,
    String activeIcon,
    String label,
  ) {
    final bool isActive = _currentIndex == index;
    
    // 如果动画控制器未初始化，直接返回不带动画的版本
    if (_animationController == null || _scaleAnimation == null) {
      return GestureDetector(
        onTap: () => _onNavItemTap(index),
        behavior: HitTestBehavior.opaque,
        child: SizedBox(
          width: 70.w,
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              SizedBox(height: 8.h),
              Image.asset(
                isActive ? activeIcon : icon, 
                width: 24.w, 
                height: 24.h,
              ),
              SizedBox(height: 4.h),
              if (isActive)
                Text(
                  label,
                  style: GoogleFonts.racingSansOne(
                    fontSize: 12.sp,
                    color: const Color(0xFF60C3FF),
                  ),
                ),

            ],
          ),
        ),
      );
    }
    
    return GestureDetector(
      onTap: () => _onNavItemTap(index),
      behavior: HitTestBehavior.opaque,
      child: AnimatedBuilder(
        animation: _animationController!,
        builder: (context, child) {
          // 只有当前选中的项目受动画影响
          final double scale = isActive && _animationController!.isAnimating
              ? _scaleAnimation!.value
              : 1.0;
          
          return Transform.scale(
            scale: scale,
            child: child,
          );
        },
        child: SizedBox(
          width: 70.w,
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              SizedBox(height: 8.h),
              Image.asset(
                isActive ? activeIcon : icon, 
                width: 24.w, 
                height: 24.h,
              ),
              SizedBox(height: 4.h),
              // 只有选中的项目才显示文字
              if (isActive)
                Text(
                  label,
                  style: GoogleFonts.racingSansOne(
                    fontSize: 12.sp,
                    color: const Color(0xFF60C3FF),
                  ),
                ),
            ],
          ),
        ),
      ),
    );
  }
}
